package com.xingyang.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xingyang.component.Syscomponent;
import com.xingyang.config.SmsConfig;
import com.xingyang.constant.RedisKey;
import com.xingyang.enums.BizCodeEnum;
import com.xingyang.enums.SendCodeEnum;
import com.xingyang.service.NotifyService;
import com.xingyang.utils.CheckUtil;
import com.xingyang.utils.CommonUtil;
import com.xingyang.utils.JsonData;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.naming.Name;
import java.util.concurrent.TimeUnit;


/**
 * 著名信仰,愿景：让技术不再难学
 **/
@Slf4j
@Service
public class NotifyServiceImpl implements NotifyService {

    @Autowired
    private Syscomponent syscomponent;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;


    private  static  final int CODE_EXPIRED=1000*60*10;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*
    * 测试发送验证码接口一主要是用于对比优化前后区别
    * */
    @Override
    @Async("ThreadPoolTaskConfig")
    public void testSend() {
//        try {
//            TimeUnit.MICROSECONDS.sleep(200);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        ResponseEntity<String> forEntity = restTemplate.getForEntity("", String.class);
        String body=forEntity.getBody();
        log.info(body);
    }

    @Override
    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {



        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);

        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);

        if(StringUtils.isNotBlank(cacheValue)){
            long ttl = Long.parseLong(cacheValue.split("_")[1]);
            //当前时间戳-验证码发送的时间戳，如果小于60秒，则不给重复发送
            long leftTime = CommonUtil.getCurrentTimestamp() - ttl;
            if( leftTime < (1000*60)){
                log.info("重复发送短信验证码，时间间隔:{}秒",leftTime);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }


        String code= CommonUtil.getRandomCode(6);
        //生成拼接好验证码
        String value = code+"_"+CommonUtil.getCurrentTimestamp();
        stringRedisTemplate.opsForValue().set(cacheKey,value,CODE_EXPIRED,TimeUnit.MILLISECONDS);

        if(CheckUtil.isEmail(to)){
            //邮箱验证码

        }else if(CheckUtil.isPhone(to)){
            //短信验证码
            syscomponent.send(to,smsConfig.getTemplateId(),code);
        }

        return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
    }

    @Override
    public boolean checkCode(SendCodeEnum userRegister, String to, String code) {

        String cacheKey = String.format(RedisKey.CHECK_CODE_KEY,userRegister.name(),to);

        String cacheValue = stringRedisTemplate.opsForValue().get(cacheKey);

        if (StringUtils.isNotBlank(cacheValue)){
            String cacheCode = cacheValue.split("_")[0];
            if (cacheCode.equalsIgnoreCase(code)){
                stringRedisTemplate.delete(code);

                return true;

            }
        }

        return false;
    }
}
